import { NextRequest, NextResponse } from 'next/server'
import { userQueries } from '@/lib/database-prisma'
import { verifyAccessToken } from '@/lib/casdoor'

export async function GET(request: NextRequest) {
  try {
    // 从cookies获取用户ID和访问令牌
    const userId = request.cookies.get('user_id')?.value
    const accessToken = request.cookies.get('access_token')?.value

    if (!userId || !accessToken) {
      return NextResponse.json({ error: '未登录' }, { status: 401 })
    }

    // 验证访问令牌
    const tokenResult = await verifyAccessToken(accessToken)
    if (!tokenResult.valid) {
      return NextResponse.json({ 
        error: tokenResult.error || '令牌无效',
        casdoorError: true // 标记这是Casdoor相关的错误
      }, { status: 401 })
    }

    // 根据用户ID获取用户信息
    const user = await userQueries.findById.get(parseInt(userId))
    if (!user) {
      return NextResponse.json({ error: '用户不存在' }, { status: 404 })
    }

    // 返回用户信息（不包含敏感信息）
    const { casdoorId, ...userInfo } = user as any
    return NextResponse.json(userInfo)

  } catch (error) {
    console.error('获取用户信息失败:', error)
    return NextResponse.json({ 
      error: '服务器错误',
      casdoorError: false
    }, { status: 500 })
  }
} 